package org.bitoy.shimmer.config;

import lombok.RequiredArgsConstructor;
import org.bitoy.shimmer.config.filter.DemoFilter;
import org.bitoy.shimmer.config.interceptor.DemoInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.Arrays;

@Configuration
@EnableWebMvc
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class WebMvcConfig implements WebMvcConfigurer {
    private final EnumConverterFactory enumConverterFactory;
    // 拦截器
    private final DemoInterceptor demoInterceptor;

    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverterFactory(enumConverterFactory);
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(demoInterceptor)
                .addPathPatterns("/**")
                .excludePathPatterns("/login", "/logout");
    }

    /**
     * 注册过滤器，可以使用@WebFilter注解代替
     */
    @Bean
    public FilterRegistrationBean<DemoFilter> demoFilter() {
        FilterRegistrationBean<DemoFilter> registrationBean = new FilterRegistrationBean<>();
        registrationBean.setFilter(new DemoFilter());
        registrationBean.setOrder(101);
        registrationBean.setName("DemoFilter");
        registrationBean.setEnabled(true);
        registrationBean.addUrlPatterns(
                "/demo",
                "/demo2"
        );
        return registrationBean;
    }

    /**
     * 直接创建匿名过滤器类实例
     */
    @Bean
    public FilterRegistrationBean anonymousFilter() {
        return new FilterRegistrationBean(
                (request, response, filterChain) -> {
                    System.out.println("执行匿名过滤器");
                    filterChain.doFilter(request, response);
                }
        ){
            {
                setOrder(102);
                setName("AnonymousFilter");
                setEnabled(true);
                setUrlPatterns(Arrays.asList("/demo","/demo1"));
            }
        };
    }

}
